/*
 * @Author: wuqingchun
 * @Date: 2024-10-21 18:53:59
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-10-31 20:54:21
 */
#ifndef __NET_TCP_CONNECTION_H__
#define __NET_TCP_CONNECTION_H__

#include <netinet/in.h>

#include "libnet.h"
#include "net_buffer.h"
#include "net_channel.h"

#include "net_event_handler.h"

class CNetTCPConnection : public INetTCPConnection
{
    // 连接状态定义
    enum EnumConnState
    {
        CONN_STATE_UINIT,
        CONN_STATE_INIT,
        CONN_STATE_CONNECTING,
        CONN_STATE_CONNECTED,
        CONN_STATE_DISCONNECTED,
    };
public:
    CNetTCPConnection(INetEventHandler& refEvHandler, INetTCPConnectionCallback& refCallback);
    ~CNetTCPConnection();

    int32_t Init(const sockaddr_in* pstAddr);

    int32_t Send(const void* pData, size_t ulDataLen);

public:

    virtual int GetFd() override final;

    virtual int32_t DealRDEvent() override final;
    virtual int32_t DealWREvent() override final;
    virtual int32_t DealERREvent() override final;
    virtual void Close() override final;
private:
    int32_t __CreateSocket();
    int32_t __Reconnect();
    ssize_t __RecvOne(void* pBuf, size_t ulBufLen);
    ssize_t __SendOne(const void* pData, size_t ulDataLen);
    int32_t __Send(const void* pData, size_t ulDataLen);

private:
    int m_iSockFd = -1;
    EnumConnState m_enState = CONN_STATE_UINIT;

    CNetBuffer m_objSendBuffer;   // 发送缓冲区

    INetEventHandler& m_refEvHandler;
    INetTCPConnectionCallback& m_refCallback;
    sockaddr_in m_stAddr;
};

#endif //__NET_TCP_CONNECTION_H__